<script setup>
import {computed,inject,getCurrentInstance} from 'vue'

const parent = inject('TabBar')   //从祖先组件中获取TabBar的实例或对象
// console.log(parent)   //为什么有四个对象
const instance = getCurrentInstance()  //允许你访问当前组件的实例
// console.log(instance)
parent.addChild(instance)
console.log(parent)

const index = parent.children.indexOf(instance)
// console.log(index)  //0,1,2,3
const props = defineProps({
  icon: {
    type: String,
    required: true,
  },
})

const iconStyle = computed(() => {
  return ['iconfont',`icon-${props.icon}`]
})
const activeClass = computed(()=>{
    return index === parent.props.modelValue ? 'active':''
})
//parent保存时TabBar传递给组件的数据
//index保存了当前TabBarItem的索引
const handleClick =() =>{
    parent.setActive(index)
   
}
</script>

<template>
  <div class="tab-bar-item" :class="activeClass" @click="handleClick">
    <i :class="iconStyle"></i>
    <slot></slot>
  </div>
</template>

<style scoped>
@import 'https://at.alicdn.com/t/c/font_4627617_cgu9v70usfw.css';

.tab-bar-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 12px;
}
.tab-bar-item i {
  font-size: 18px;
}
.tab-bar-item.active {  
    color: red; /* 高亮颜色 */  
}  
</style>
